<?php

namespace App\Console\Commands\BlockPool;

use App\Models\Device;
use App\Models\Order;
use App\Models\OrderLog;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderStatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order-status';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '矿机托管到期，修改订单状态';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Order::where('status', 1)
            ->where('finish_at', '<', now())
            ->chunk(1000, function ($order_list) {
                foreach ($order_list as $order) {
                    logger("矿机托管到期，更新矿机状态，订单ID：{$order->id}");
                    try {
                        DB::transaction(function () use ($order) {
                            // 保存订单
                            $order = Order::lockForUpdate()->find($order->id);
                            $order->status = 0;
                            $order->save();

                            // 释放库存
                            $orderLogs = OrderLog::where('user_id', $order->user_id)->where('order_id', $order->id)->where('status', 1)->lockForUpdate()->get();
                            foreach ($orderLogs as $orderLog) {
                                $orderLog->status = 0;
                                $orderLog->save();

                                $device = Device::where('user_id', $order->user_id)->where('id', $orderLog->device_id)->lockForUpdate()->first();
                                if ($device) {
                                    $device->use = $device->use - min($device->use, $orderLog->use);
                                    $device->save();
                                }
                            }

                        });
                    } catch (Exception $exception) {
                        logger("更新矿机状态失败");
                        Log::error($exception);
                    }
                }
            });
    }
}
